package com.cmhi.base.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DevInfoManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.chinamobile.SWDevInfoManager;
import com.cmhi.base.R;
import com.cmhi.base.action.HandlerAction;
import com.cmhi.base.entity.ShareInfo;
import com.cmhi.base.provider.BimDataManager;
import com.cmhi.base.receiver.SoftBroadcastReceiverInterface;
import com.cmhi.base.utils.BimTools;
import com.cmhi.base.config.StaticConst;
import com.cmhi.base.entity.AppInfo;
import com.cmhi.base.receiver.SoftBroadcastReceiver;
import com.cmhi.base.utils.ToastUtils;
import com.softmbh.kellyplatform.KellyPlatform;
import com.softmbh.kellyplatform.bean.AccountBean;
import com.softmbh.kellyplatform.bean.BusinessInfoBean;
import com.softmbh.kellyplatform.bean.DeviceUserInfo;
import com.softmbh.kellyplatform.bean.DialogConfigBean;
import com.softmbh.kellyplatform.bean.InforMation;
import com.softmbh.kellyplatform.bean.LicenseBean;
import com.softmbh.kellyplatform.bean.ProvinceConfigInfoBean;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.CheckerUtils;
import com.softmbh.kellyplatform.util.LocalDeviceInfo;

import java.util.List;
import java.util.Map;

public abstract class BaseMainActivity extends AppCompatActivity implements HandlerAction, KellyPlatform.SoftInerface, SoftBroadcastReceiverInterface {

    //申请权限失败对话框
    private AlertDialog permissionDialog;
    //申请权限自定义返回 code 值
    private final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 100;
    protected LinearLayout llLoading, llDownLoading, llCheckSpace;
    protected TextView tvLoading, tvDownloadingTop, tvDownloadingPercent, tvVersionTemp;
    protected ProgressBar pbDownloadingTop, pbDownloading;
    protected KellyPlatform kellyPlatform;
    //广播接收器
    private SoftBroadcastReceiver softBroadcastReceiver;
    //开机后可以进行网络相关操作的时间，单位：秒
    protected final long myBootTime = 35;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId() == 0 ? R.layout.activity_main : getLayoutId());
        //去除windowBackground
        getWindow().setBackgroundDrawable(null);
        kellyPlatform = initKellyPlatform();
        initView();
        initData();
    }
    protected void initData() {}


    protected abstract int getLayoutId();

    protected abstract KellyPlatform initKellyPlatform();

    protected void startExecute() {
        showLoadingView();
        if (kellyPlatform == null) {
            kellyPlatform = initKellyPlatform();
        }
        kellyPlatform.startExecute();
    }
    protected void registerBroadcastReceiver() {
        softBroadcastReceiver = new SoftBroadcastReceiver(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_CDN_UPDATE);
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_ZW_ACTIVATE_COMPLETED);
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_ZW_ACTIVATE_FAILER);
        registerReceiver(softBroadcastReceiver, intentFilter);
    }
    protected void initView() {
        llLoading = findViewById(R.id.llLoading);
        llDownLoading = findViewById(R.id.llDownLoading);
        llCheckSpace = findViewById(R.id.llCheckSpace);
        tvLoading = findViewById(R.id.tvLoading);
        tvDownloadingTop = findViewById(R.id.tvDownloadingTop);
        tvDownloadingPercent = findViewById(R.id.tvDownloadingPercent);
        pbDownloadingTop = findViewById(R.id.pbDownloadingTop);
        pbDownloading = findViewById(R.id.pbDownloading);

    }

    public void showDownloadingView() {
        llLoading.setVisibility(View.GONE);
        if (llDownLoading.getVisibility() != View.VISIBLE) {
            llDownLoading.setVisibility(View.VISIBLE);
        }
    }

    public void hiddenAllView() {
        llLoading.setVisibility(View.GONE);
        llDownLoading.setVisibility(View.GONE);
    }

    public void showLoadingView() {
        llDownLoading.setVisibility(View.GONE);
        if (llLoading.getVisibility() != View.VISIBLE) {
            llLoading.setVisibility(View.VISIBLE);
        }
    }

    //检查权限，Android 6.0 动态申请权限
    protected boolean checkPermission() {
        //当用户拒绝权限且选择不再弹出申请对话框时，避免后台重复无用申请，因为是在 onResume 中调用，不做判断会一直重复调用
        if (permissionDialog != null && permissionDialog.isShowing()) {
            return false;
        }
        //检查权限是否通过，PackageManager.PERMISSION_GRANTED 表示同意授权
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            //if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //Toast.makeText(this, "请开通相关权限，否则无法正常使用！", Toast.LENGTH_LONG).show();
            //}
            //申请权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            return false;
        }
    }


    //硬件检测不通过
    @SuppressLint("SetTextI18n")
    protected boolean hardwareDetectionFailed() {

        //if (true) return false;//跳过硬件检测
        //CPU 核心数
        int cpuCores = CheckerUtils.getDeviceCPUCores();
        //CPU 频率，单位 KHz
        long cpuFrequency = Long.parseLong(CheckerUtils.getDeviceCpuCoresHz());
        //可用存储大小，单位 B
        long availROMSize = BimTools.getAvailROMMem();
        //可用内存，单位 B
        long availRAMSize = BimTools.getAvailRAMMem();
        //总内存，单位 B
        long totalRAMSize = BimTools.getTotalRAMMem();
        AppUtils.debugLog("cpuCores : " + cpuCores +
                ", cpuFrequency : " + cpuFrequency +
                ", availableRomLong : " + availROMSize +
                ", availableMemoryLong : " + availRAMSize +
                ", totalMemory : " + totalRAMSize);
        AppUtils.debugLog(cpuCores + "核" +
                ", " + cpuFrequency + "KHz频率" +
                ", 可用存储大小 : " + availROMSize / 1024 / 1024 + "MB" +
                ", 可用内存 : " + availRAMSize / 1024 / 1024 + "MB" +
                ", 总内存 : " + totalRAMSize / 1024 / 1024 + "MB");
        boolean result = (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) ||
                (cpuCores < 3 && cpuFrequency > 0 && cpuFrequency < 1024 * 1024) ||
                (availROMSize != 0L && availROMSize < 400 * 1024 * 1024L) ||
                (availRAMSize != 0L && availRAMSize < 250 * 1024 * 1024L) ||
                (totalRAMSize != 0L && totalRAMSize < 900 * 1024 * 1024L);
        AppUtils.debugLog("hardwareDetectedFail : " + result);
        if (result) {
            hiddenAllView();
            llCheckSpace.setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.tvBrand)).setText("设备厂商：" + BimDataManager.getAppInfoInstance().getValue(AppInfo.BRAND));
            ((TextView) findViewById(R.id.tvModel)).setText("设备型号：" + Build.MODEL);
            TextView hardwareAndroidVersionText = findViewById(R.id.tvAndroidVersion);
            hardwareAndroidVersionText.setText("安卓版本：" + Build.VERSION.RELEASE + " (" + Build.VERSION.SDK_INT + ")");
            ((TextView) findViewById(R.id.tvCpuModel)).setText("芯片型号：" + CheckerUtils.getCpuInfo());
            TextView hardwareCpuParameterText = findViewById(R.id.tvCpuParameter);
            hardwareCpuParameterText.setText("芯片参数：" + cpuCores + "核  " + CheckerUtils.getDeviceCpuCoresGHz() + "GHz");
            TextView hardwareRomText = findViewById(R.id.tvRom);
            hardwareRomText.setText("存储空间：" + BimTools.showROMInfo());
            TextView hardwareRamText = findViewById(R.id.tvRam);
            hardwareRamText.setText("内存大小：" + (
                    (availRAMSize < 250 * 1024 * 1024 && availRAMSize > 249 * 1024 * 1024) ? "249 MB" :
                            BimTools.showRAMInfo()));
            TextView hardwareMessageText = findViewById(R.id.tvNoSpace);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                hardwareMessageText.setText("\n抱歉，系统版本过高，该设备暂不支持安装软终端！");
                hardwareAndroidVersionText.setTextColor(Color.parseColor("#FF4F4F"));
            } else if (cpuCores < 3 && cpuFrequency > 0 && cpuFrequency < 1024 * 1024) {
                hardwareMessageText.setText("\n抱歉，系统配置过低，该设备暂不支持安装软终端！");
                hardwareCpuParameterText.setTextColor(Color.parseColor("#FF4F4F"));
            } else if (availROMSize != 0L && availROMSize < 400 * 1024 * 1024L) {
                hardwareMessageText.setText("\n抱歉，系统存储空间不足，请确保有400MB的可用空间！");
                hardwareRomText.setTextColor(Color.parseColor("#FF4F4F"));
            } else if (availRAMSize != 0L && availRAMSize < 250 * 1024 * 1024L) {
                hardwareMessageText.setText("\n抱歉，系统运行内存不足，请确保有250MB的可用内存！");
                hardwareRamText.setTextColor(Color.parseColor("#FF4F4F"));
            } else if (totalRAMSize != 0L && totalRAMSize < 900 * 1024 * 1024L) {
                hardwareMessageText.setText("\n抱歉，系统运行内存不足，请确保有1GB的总内存！");
                hardwareRamText.setTextColor(Color.parseColor("#FF4F4F"));
            }
            findViewById(R.id.btnExit).setOnClickListener(v -> {
                //解决牌照方未退出的问题
                AppUtils.killPackageProcesses(BimTools.getAppContext(), "com.gitv.launcher.soft");
                AppUtils.killPackageProcesses(BimTools.getAppContext(), "tv.icntv.ott.soft.ypjs");
                AppUtils.killPackageProcesses(BimTools.getAppContext(), "com.chinamobile.activate.soft");
                exit();
            });
        } else {
            llCheckSpace.setVisibility(View.GONE);
        }
        return result;
    }

    //当应用请求权限时，系统将向用户显示一个对话框，当用户响应时，系统将调用应用的 onRequestPermissionsResult()方法，
    //向其传递用户响应，处理对应的场景
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {//If request is cancelled, the result arrays are empty.
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {//选择始终允许
                    AppUtils.debugLog("onRequestPermissionsResult granted");
                    initData();
                } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {//选择拒绝
                    AppUtils.debugLog("onRequestPermissionsResult denied");
                    showWaringDialog(2, permissions[i]);
                } else {//选择不再询问
                    AppUtils.debugLog("onRequestPermissionsResult denied and never ask again");
                    showWaringDialog(3, permissions[i]);
                }
            }
        }
    }


    //申请权限被拒绝，弹出友好提示对话框
    protected void showWaringDialog(int type, String permission) {
        if (permissionDialog == null || !permissionDialog.isShowing()) {
            String message = "";
            if (type == 2) {
                message = "请开通读写权限，否则无法正常使用！";
            } else if (type == 3) {
                message = "已选择不再询问，自动打开系统设置失败！\n请手动前往 设置->应用->魔百和软终端->权限，打开读写权限，否则无法正常使用！";
            }
            permissionDialog = new AlertDialog.Builder(this)
                    .setTitle("警告！")
                    .setMessage(message)
                    .setNegativeButton("确定", (permissionDialog, which) -> {
                        permissionDialog.dismiss();
                        if (type == 2) {
                            ActivityCompat.requestPermissions(this,
                                    new String[]{permission}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                        } else if (type == 3) {
                            try {
                                //启动系统设置
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                //注意就是"package",不用改成自己的包名
                                Uri uri = Uri.fromParts("package", BimTools.getAppContext().getPackageName(), null);
                                intent.setData(uri);
                                //正常需要使用 startActivityForResult，再添加 onActivityResult 回调函数再次检查权限，
                                //因为现在 onResume 中会检查权限，所有省去
                                startActivity(intent);
                                exit();
                            } catch (Exception e) {
                                e.printStackTrace();
                                showWaringDialog(3, permission);
                            }
                        }
                    })
                    .setPositiveButton("退出", (permissionDialog, which) -> exit())
                    .setCancelable(false).show();
        }
    }
    protected void startZwActivate() {
        try {
            AppUtils.debugLog("start ZwActivate");
            startActivity(new Intent("com.chinamobile.activate.soft"));
            AppUtils.debugLog("start ZwActivate finish");
        } catch (Exception e) {
            AppUtils.debugLog("start ZwActivate error : " + e);
            e.printStackTrace();
            showErrorDialogOneBtnExit("打开卓望首活失败！");
        }
    }
    protected void startGitv(String launcher) {
        try {
            AppUtils.debugLog("start GITV");
            BimDataManager.getAppInfoInstance().update(AppInfo.LAUNCHER_ACTION, launcher);
            BimDataManager.getShareInfoManager().update(ShareInfo.KEY_LAUNCHER, launcher);
            startActivity(new Intent("com.gitv.launcher"));
            AppUtils.debugLog("start GITV finish");
        } catch (Exception e) {
            AppUtils.debugLog("start GITV error : " + e);
            e.printStackTrace();
            showErrorDialogOneBtnExit("打开银河桌面失败！");
        }
    }

    //设置卓望关键参数数据
    public void updateZwData(String key, String value) {
        SWDevInfoManager.getInstance(this)
                .update(key,
                        value,
                        DevInfoManager.Default_Attribute,
                        result -> {// 0 成功，否则失败
                            AppUtils.debugLog(key + " : " + value + " : " + (result == 0 ? "success" : result));
                        });
    }

    //获取卓望关键参数数据
    protected void getZwData(String key) {
        SWDevInfoManager
                .getInstance(this)
                .getValue(key, value ->
                        AppUtils.debugLog(key + " : " + value));
    }

    protected void startNewTV(String launcher,String newTvAppId) {
        try {
            BimDataManager.getAppInfoInstance().update(AppInfo.LAUNCHER_ACTION, launcher);
            BimDataManager.getShareInfoManager().update(ShareInfo.KEY_LAUNCHER, launcher);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            ComponentName componentName = new ComponentName("tv.icntv.ott.soft.ypjs", "tv.icntv.ott.icntv");
            intent.setComponent(componentName);
            intent.putExtra("softmac", BimDataManager.getAppInfoInstance().getValue(AppInfo.SOFT_VIRTUAL_MAC));
            intent.putExtra("appId", newTvAppId);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            AppUtils.debugLog("start NewTV finish");
        } catch (Exception e) {
            AppUtils.debugLog("start NewTV error : " + e);
            e.printStackTrace();
            showErrorDialogOneBtnExit("打开未来电视失败！");
        }
    }

    protected void showErrorDialogOneBtnExit(String message) {
        getHandler().post(() -> {
            hiddenAllView();
            kellyPlatform.showErrorMessage("错误", "", message,
                    true, "", "退出",
                    buttonText -> exit());
        });
    }  protected void showErrorDialogOneBtnExit(String message,String subTitle) {
        getHandler().post(() -> {
            hiddenAllView();
            kellyPlatform.showErrorMessage("错误", subTitle, message,
                    true, "", "退出",
                    buttonText -> exit());
        });
    }

    //结束进程
    protected void exit() {
        finish();
        //调用系统 API 结束进程
        android.os.Process.killProcess(android.os.Process.myPid());
        //结束整个虚拟机进程，注意如果在 manifest 里用 android:process 给 APP 指定了不止一个进程，则只会结束当前进程
        System.exit(0);
    }



    //读取关键参数
    protected void readKeyParameters() {
        getZwData(DevInfoManager.PHONE);
        getZwData(DevInfoManager.SPASSWORD);
        getZwData(DevInfoManager.ACCOUNT);
        getZwData(DevInfoManager.APASSWORD);
        getZwData(DevInfoManager.STB_MAC);
        getZwData(DevInfoManager.STB_SN);
        getZwData(DevInfoManager.PLAT_URL);
        getZwData(DevInfoManager.PLAT_URLBACK);
        getZwData(DevInfoManager.CMSURL);
        getZwData(DevInfoManager.CMSURLBACK);
        getZwData(DevInfoManager.HDCRURL);
        getZwData(DevInfoManager.EPG_ADDRESS);
        getZwData(DevInfoManager.CDN_ADDRESS);
        getZwData(DevInfoManager.CDN_ADDRESS_BACK);
        getZwData(DevInfoManager.TV_ID);
        getZwData(DevInfoManager.MANUFACTURER);
        getZwData(DevInfoManager.MODEL_NAME);
        getZwData(DevInfoManager.FIRMWARE_VERSION);
        getZwData(DevInfoManager.CDN_TYPE);
        getZwData(DevInfoManager.PLAT_URL_ZTE);
        getZwData(DevInfoManager.PLAT_URL_ZTE_BACK);
        getZwData(DevInfoManager.CDN_DISPATCH_URL);
        getZwData(DevInfoManager.CDN_DISPATCH_URL_BACK);
        getZwData(DevInfoManager.LAUNCHER);
        getZwData(DevInfoManager.OTT_TERMINAL_TYPE);
        getZwData(DevInfoManager.ACTIVE_USER_TYPE);

        getZwData(DevInfoManager.OTT_TERMINAL_BRAND);
        getZwData(DevInfoManager.CHANNEL_TYPE);
    }
    protected boolean isSystemApp(String packageName) {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_CONFIGURATIONS);
            return "android.uid.system".equals(packageInfo.sharedUserId);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //屏蔽返回键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        AppUtils.debugLog("生命周期=>onDestroy");
        if (kellyPlatform != null) {
            kellyPlatform.destroy();
            kellyPlatform = null;
        }
        if(softBroadcastReceiver!=null){
            unregisterReceiver(softBroadcastReceiver);
        }
        removeCallbacks();
        ToastUtils.cancel();
        super.onDestroy();
    }

    @Override
    public void onLicense(LicenseBean licenseBean) {
        AppUtils.debugLog("licenseBean=>{" +
                "license:" + licenseBean.license + ";" +
                "sn:" + licenseBean.sn + ";" +
                "stbId:" + licenseBean.stbId + ";" +
                "licenseGroup:" + licenseBean.licenseGroup + ";" +
                "accountState:" + licenseBean.accountState + "}"
        );
    }

    @Override
    public void onConfirmComplete() {
        AppUtils.debugLog("onConfirmComplete");
    }

    @Override
    public void onUserContinue(byte b) {

    }

    @Override
    public void onNetStateChange(boolean b) {
        if (b) {
            if (llLoading.getVisibility() == View.VISIBLE) {
                tvLoading.setText("正在加载，请耐心等候……");
            }
            if (llDownLoading.getVisibility() == View.VISIBLE) {
                pbDownloadingTop.setVisibility(View.VISIBLE);
                tvDownloadingTop.setText(" 正在加载，请耐心等候……");
                pbDownloading.setProgressDrawable(getResources().getDrawable(R.drawable.progress_download));
            }
        } else {
            if (llLoading.getVisibility() == View.VISIBLE) {
                tvLoading.setText("正在连接网络，请耐心等候……");
            }
            if (llDownLoading.getVisibility() == View.VISIBLE) {
                pbDownloadingTop.setVisibility(View.GONE);
                tvDownloadingTop.setText("网络已断开，请检查网络");
                pbDownloading.setProgressDrawable(getResources().getDrawable(R.drawable.progress_download_error));
            }
        }
    }

    @Override
    public void onMediaCodecLevel(String s) {
        AppUtils.debugLog("4K====>" + s);
        BimDataManager.getAppInfoInstance().update(AppInfo.DEVICE_MEDIA_INFO, s);
        BimDataManager.getShareInfoManager().update(ShareInfo.KEY_DEVICE_MEDIA_INFO, s);
    }

    @Override
    public void onDownloadComplete(Map<String, String> installPackage) {
        AppUtils.debugLog("onDownloadComplete");
    }

    @Override
    public void onProgress(String packageName, String apkName, int progress) {

    }

    @Override
    public void onIcnTvInitResult(boolean isSuccess, InforMation inforMation) {
    }

    @Override
    public boolean onPreShowErrorDialog(String title, String message, int errorCode) {
        return false;
    }

    @Override
    public void onAccountInfo(String backPhone, List<AccountBean> dataBeans) {

    }

    @Override
    public void onBusinessInfo(BusinessInfoBean.DataBean dataBean) {

    }

    @Override
    public void onDialogText(String action, DialogConfigBean.DataBean dataBean) {


    }

    @Override
    public void onProvinceInfo(ProvinceConfigInfoBean.DataBean dataBean, LocalDeviceInfo localDeviceInfo) {

    }

    @Override
    public void onUserInfoByDevice(DeviceUserInfo.DataBean bean) {

    }

    @Override
    public void onReceive(Intent intent) {

    }
}
